#! /bin/bash

source "$(dirname ${0})/generic.sh";

setCwdToMyDir;

declare -r BASEDIR="..";
declare -r TEMPLATES_DIR="${BASEDIR}/templates";
declare -r FILELIST="${TEMPLATES_DIR}/filelist";
declare -r PATTERNS_FILE="${TEMPLATES_DIR}/patterns";

if [ -n "${1}" ];
then                    \
  GEN_ONLY_FILE="${1}"; \
fi;

awk 'BEGIN {                                                    \
    FS=":";                                                     \
  }                                                             \
  {                                                             \
    patterns[$1] = $2;                                          \
  }                                                             \
  END {                                                         \
    num_patterns = 0;                                           \
    for (i in patterns) {                                       \
      cmd = patterns[i];                                        \
      cmd | getline result;                                     \
      close(cmd);                                               \
      cmds[num_patterns++] = "sed -e \"s/" i "/" result "/g\""; \
    }                                                           \
    fileList = "'"${FILELIST}"'";                               \
    while ( getline < fileList ) {                              \
      if (length("'"${GEN_ONLY_FILE}"'") != 0) {                \
        if ($1 != "'"${GEN_ONLY_FILE}"'")                       \
          continue;                                             \
      }                                                         \
      sourceFile = "'"${TEMPLATES_DIR}"'/" $1;                  \
      destFile = "'"${BASEDIR}"'/" $2;                          \
      count = 0;                                                \
      for (i in cmds) {                                         \
        if (count++ > 0)                                        \
          sourceFile = ".tmp" (count - 1);                      \
        cmd = cmds[i] " <" sourceFile " >.tmp" count;           \
        cmd | getline;                                          \
        close(cmd);                                             \
      }                                                         \
      cmd = "cp -f .tmp" count " " destFile;                    \
      cmd | getline;                                            \
      close(cmd);                                               \
      if (length("'"${GEN_ONLY_FILE}"'") != 0) {                \
        exit 0;                                                 \
      }
    }                                                           \
  }' <"${PATTERNS_FILE}";
checkReturnCode "FAILED -- Template substitution" true;
rm -f .tmp*;
